package com.bawei.module_live.version2.mvi.viewmodel

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.bawei.lib_common.mvi.base.BaseViewModel
import com.bawei.module_live.version2.mvi.intent.LiveIntent
import com.bawei.module_live.version2.mvi.model.repository.LiveRepository
import com.bawei.module_live.version2.mvi.state.LiveState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch


class LiveViewModel : BaseViewModel<LiveIntent>(){
    private val repository: LiveRepository by  lazy { LiveRepository() }

    private var liveFlow = MutableStateFlow<LiveState>(LiveState.Init)
    private var GetRedPackFlow = MutableStateFlow<LiveState>(LiveState.Init)

    val liveFlow_ = liveFlow.asStateFlow()
    val GetRedPackFlow_ = GetRedPackFlow.asStateFlow()
    //1:根据意图发起网络请求
    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is LiveIntent.getSimpleType-> getSimpleTypeData()
                    is LiveIntent.Getredpacket->GetRedPacketData()
                }
            }
        }
    }
    //2:根据网络请求结果更新状态流
    private fun getSimpleTypeData() {
        viewModelScope.launch {
            repository.getSimpleType()
            .catch { e->
                liveFlow.value = LiveState.Failed(e.message.toString())
            }.filter {
                it != null
            }.collect{
                if(it.code == 200){
                    if(it.data.isEmpty()){
                        liveFlow.value = LiveState.Empty
                    }else{
                        liveFlow.value = LiveState.VideoSuccess(it.data)
                    }
                }else{
                    liveFlow.value = LiveState.Failed(it.msg)
                }
            }

        }
    }
    private fun GetRedPacketData() {
        viewModelScope.launch {
            repository.getRedPacket()
                .catch { e->
                    GetRedPackFlow.value = LiveState.Failed(e.message.toString())
                }.filter {
                    it != null
                }.collect{
                    if(it.code == 200){
                        if(!it.data){
                            GetRedPackFlow.value = LiveState.Empty
                        }else{
                            GetRedPackFlow.value = LiveState.GetRedPacketSuccess(it.data)
                        }
                    }else{
                        GetRedPackFlow.value = LiveState.Failed(it.msg)
                    }
                }

        }
    }



}